#内置了登录、登出可以直接拿来使用
import random
import string

from django.contrib.auth import get_user_model, login,logout

from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_http_methods
from django.contrib import messages
from zlauth.forms import LoginForm,RegistrationForm
from zlauth.models import CaptchaModel

User = get_user_model()

# Create your views here. view类似  java中controller

#登录方法
# @require_http_methods(['GET','POST'])
def zlogin(request):
    #get请求直接跳登录页面
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember_me = form.cleaned_data.get('remember_me')
            print(f'----email: {email}, ----password: {password}, ----remember_me: {remember_me}')

            user = User.objects.filter(email=email).first()

            if user is None:
                print('邮箱不存在，请注册')
                messages.error(request, '邮箱不存在，请注册')
                return render(request, 'login.html', {'form': form})  # 传递表单实例
            else:
                if user.check_password(password):
                    login(request, user)
                    if not remember_me:
                        request.session.set_expiry(0)
                    return redirect('blog:index')
                else:
                    print('邮箱或者密码错误')
                    form.add_error('email', '邮箱或者密码错误')
                    # 修复：使用render而不是redirect，并修正语法错误
                    return render(request, 'login.html', {'form': form})
        # 处理表单验证失败的情况
        print('344343')
        return render(request, 'login.html', {'form': form})

# @require_http_methods(['GET', 'POST'])
# def zlogin(request):
#     if request.method == 'GET':
#         return render(request, 'login.html')
#     else:
#         form = LoginForm(request.POST)
#         if form.is_valid():
#             email = form.cleaned_data.get('email')
#             password = form.cleaned_data.get('password')
#             remember_me = form.cleaned_data.get('remember_me')
#             print(f'----email: {email}, ----password: {password}, ----remember_me: {remember_me}')
#
#             user = User.objects.filter(email=email).first()
#
#             if user is None:
#                 print('邮箱不存在，请注册')
#                 messages.error(request, '邮箱不存在，请注册')
#                 return render(request, 'login.html', {'form': form})  # 传递表单实例
#             else:
#                 if user.check_password(password):
#                     login(request, user)
#                     if not remember_me:
#                         request.session.set_expiry(0)
#                     return redirect('blog:index')
#                 else:
#                     print('邮箱或者密码错误')
#                     form.add_error('email', '邮箱或者密码错误')
#                     # 修复：使用render而不是redirect，并修正语法错误
#                     return render(request, 'login.html', {'form': form})
#
#         # 处理表单验证失败的情况
#         print('344343')
#         return render(request, 'login.html', {'form': form})
"""
 退出跳转到首页
"""
def zlogout(request):
    logout(request)
    #跳转至 首页
    return redirect('blog:index')

@require_http_methods(['GET','POST'])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            print(f'----email: {email}, ----username: {username}, ----password: {password}')
            #添加用户信息，成功进行跳转
            User.objects.create_user(username=username, email=email, password=password)
            #重定向到登录页面
            return redirect('zlauth:login')
        else:
            print(form.errors)
            #重新跳转到注册页面 为什么 zlauth:register跳转 应该是 zlauth目录 下的  register方法
            return redirect(render('zlauth:register'))


#发送验证码
def send_email_captcha(request):
    email=request.GET.get('email')
    if email:
         #生成验证码（随机4位阿拉伯数字） 之前报错是导包错误了
         num_list=random.sample(string.digits,4)
         #变成字符串
         captcha=''.join(num_list)
         #根据邮箱更新验证码
         CaptchaModel.objects.update_or_create(email=email,captcha=captcha)
         print(f'captcha:{captcha}')
         #调用封装方法发送邮件
         send_mail('zpblog博客注册验证码',f'您的注册验证码是{captcha}，有效期5分钟',from_email=None,recipient_list=[email])
         result={
             'code':200,
             'msg':'成功'
         }
         return JsonResponse(result,safe=False)
    else:
        result = {
            'code': 400,
            'msg': '失败'
        }
        return JsonResponse(result,safe=False)

